﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text;
using AttachReminderAddIn.Properties;

namespace AttachReminderAddIn
{
    public static class SearchTermManager
    {
        // This is more for future functionality than now.
        private const string DataFileName = "AttachReminder.dat";

        public static List<string> SearchTerms { get; private set; }

        static SearchTermManager()
        {
            InitializeSearchTerms();
        }
        
        private static void ParseSearchTerms(string searchTerms)
        {
            SearchTerms = new List<string>();

            using (var sr = new StringReader(searchTerms))
            {
                while (true)
                {
                    var line = sr.ReadLine();

                    if (line != null)
                    {
                        SearchTerms.Add(line);
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }

        // Reverts to default search terms.
        public static void RevertSearchTerms()
        {
            ParseSearchTerms(Resources.DefaultAttachSearchStrings);
        }

        private static void InitializeSearchTerms()
        {
            try
            {
                var appUserIsf = IsolatedStorageFile.GetUserStoreForAssembly();

                // create an isolated storage stream...
                using (var userDataFile = new IsolatedStorageFileStream(DataFileName, FileMode.Open, appUserIsf))
                {
                    // create a reader to the stream...
                    using (var readStream = new StreamReader(userDataFile))
                    {
                        ParseSearchTerms(readStream.ReadToEnd());
                    }
                }
            }
            catch (FileNotFoundException)
            {
                // If the isolated storage file does not exist, return the default.
                RevertSearchTerms();
            }
        }
    }
}
